package fr.insee.rome.io.reader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fr.insee.rome.bean.Metier;

public class RegexMetierReader implements MetierReader {

	private static final Pattern
		patternMetier = Pattern.compile("codRome=(\\d{5})\">([^0-9<]+)</a>");
	;
	
	private static MetierReader instance = null;
	
	private RegexMetierReader(){}
	
	public static MetierReader getInstance(){
		if(instance == null){
			instance = new RegexMetierReader();
		}
		return instance;
	}
	
	public SortedSet<Metier> read(InputStream stream) throws IOException {
		
		Reader reader = new InputStreamReader(stream);
		BufferedReader buffer = new BufferedReader(reader);
		StringBuffer html = new StringBuffer();
		String line;
		while ((line = buffer.readLine()) != null) {
			html.append(line);
		}
		
		buffer.close();
		reader.close();
		
		return this.parse(html.toString());
	}
	
	private SortedSet<Metier> parse(String html){
		
		SortedSet<Metier> metiers = new TreeSet<Metier>();
		Matcher matcher = patternMetier.matcher(html);
		while(matcher.find()){
			
			String
				code = matcher.group(1),
				libelle = matcher.group(2)
			;
			
			Metier metier = new Metier();
			metier.setCode(code);
			metier.setLibelle(libelle);
			
			metiers.add(metier);
		}
		
		return metiers;
	}
}
